package com.xbongbong.paas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.dao.PaasUserDao;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasUserEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasUserModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaasTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 汪腾伟
 * @date: Created in 2022/1/10 9:34
 * @description： paas团队model层
 */
@Service("paasTeamUserModel")
public class PaasUserModelImpl implements PaasUserModel {

    @Resource
    private PaasUserDao paasTeamUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    /**
     * 查询paas表单团队信息
     *
     * @param map
     * @return
     */
    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return paasTeamUserDao.findBaseEntitys(map);
    }

    /**
     * 批量插入paas团队用户信息
     *
     * @param paasUserEntities
     */
    @Override
    public void insertBatch(List<PaasUserEntity> paasUserEntities) throws XbbException {
        insertBatch(paasUserEntities, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insertBatch(List<PaasUserEntity> paasUserEntities, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        paasTeamUserDao.insertBatch(paasUserEntities);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_FORM_DATA_TEAM, paasUserEntities);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_FORM_DATA_TEAM));
        }
        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }


    /**
     * 查询paas表单团队信息
     *
     * @param map
     * @return
     */
    @Override
    public List<PaasUserEntity> findEntitys(Map<String, Object> map) {
        return paasTeamUserDao.findEntitys(map);
    }

    /**
     * 更新paas表单团队信息
     *
     * @param paasUserUpdateEntities
     */
    @Override
    public void updateBatch(List<PaasUserEntity> paasUserUpdateEntities) {
        paasTeamUserDao.updateBatch(paasUserUpdateEntities);
    }

    /**
     * 批量更新paas团队信息
     *
     * @param corpid 公司id
     * @param idIn 主数据id
     * @param delUserTeamList 需要删除的团队
     * @param isMain 是否是主负责人标识 1：负责人 0：协同人
     * @param del 删除标识
     */
    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> delUserTeamList, Integer isMain, Integer del) throws XbbException {
        batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, isMain, del, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> delUserTeamList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        paasTeamUserDao.batchUpdateByIdIn(corpid, idIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : delUserTeamList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_FORM_DATA_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaasTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_FORM_DATA_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }


    /**
     * 只往数据库插入，但是不插入es
     *
     * @param paasUserInsertEntities
     */
    @Override
    public void insertNoEsBatch(List<PaasUserEntity> paasUserInsertEntities) {
        paasTeamUserDao.insertBatch(paasUserInsertEntities);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return paasTeamUserDao.getEntitysCount(param);
    }



    /**
     * 获取paas团队信息
     *
     * @param id
     * @param corpid
     * @return
     */
    @Override
    public PaasUserEntity getByKey(Long id, String corpid) {
        return paasTeamUserDao.getByKey(id, corpid);
    }

    /**
     * 编辑协同人编辑权限
     *
     * @param paasUserEntity
     */
    @Override
    public void updateEditFormPer(PaasUserEntity paasUserEntity) throws XbbException{
        updateFormTeam(paasUserEntity);
    }

    /**
     * paas表单编辑标签
     *
     * @param paasUserEntity
     */
    @Override
    public void editLabel(PaasUserEntity paasUserEntity) throws XbbException{
        updateFormTeam(paasUserEntity);
    }

    private void updateFormTeam(PaasUserEntity paasUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        paasUserEntity.setUpdateTime(updateTime);
        paasTeamUserDao.update(paasUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = paasUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_FORM_DATA_TEAM.getType() + "_" + corpid + "_" + paasUserEntity.getId());
        insertDTO.setParent(corpid + "_" + paasUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_FORM_DATA_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param dataIdIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        paasTeamUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_FORM_DATA_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_FORM_DATA_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    @Override
    public List<PaasUserEntity> getPaasUserList(String corpid, Long dataId, Integer isMain) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("dataId", dataId);
        if (isMain != null) {
            param.put("isMain", isMain);
        }
        return findEntitys(param);
    }

    @Override
    public void deleteBatch(String corpid, List<PaasUserEntity> paasUserList, Integer del) throws XbbException {
        if (CollectionsUtil.isEmpty(paasUserList)) {
            return;
        }
        List<Long> removeIdList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasUserEntity paasUserEntity : paasUserList) {
            removeIdList.add(paasUserEntity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_FORM_DATA_TEAM.getType() + "_" + corpid + "_" + paasUserEntity.getId());
            insertDTO.setParent(corpid + "_" + paasUserEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("del", del);
            map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_FORM_DATA_TEAM);
            insertDTOList.add(insertDTO);
        }


        paasTeamUserDao.batchUpdateByIdIn(corpid, removeIdList, null, del);
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
    }
}
